package com.springcloud.gateway.dynamic;

import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionWriter;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @version V1.0
 * @Author 宋聚智
 * @Date 2019/10/31 11:49
 * @description
 * @Modify By：
 * @ModifyTime： 2019/10/31
 * @Modify marker：
 **/
@Service
public class DynamicRouteService implements ApplicationEventPublisherAware {
    //路由操作实例
   private final RouteDefinitionWriter routeDefinitionWriter;
   //收件实例
   private ApplicationEventPublisher publisher;

   public DynamicRouteService(RouteDefinitionWriter routeDefinitionWriter){
       this.routeDefinitionWriter=routeDefinitionWriter;
   }

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.publisher=applicationEventPublisher;
    }


    public String update(RouteDefinition definition){
       this.routeDefinitionWriter.delete(Mono.just(definition.getId()));
       this.routeDefinitionWriter.save(Mono.just(definition)).subscribe();
       this.publisher.publishEvent(new RefreshRoutesEvent(this));
       return "update success";
    }

    public String updateList(List<RouteDefinition> routeDefinitionList){
       routeDefinitionList.forEach(this::update);
       return "update done";
    }


    public String delete(String id){
       this.routeDefinitionWriter.delete(Mono.just(id));
       return "delete success";
    }
}
